<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-zhao.jpg">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-zhao.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-zhao.png">
  <link rel="mask-icon" href="/images/logo-zhao.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"zjybjea.cn","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="背包问题给定一组物品，每种物品都有自己的重量和价值，现有一个背包，能承受的重量有限，在受限制的重量下，去取若干物品使总价值最大。">
<meta property="og:type" content="article">
<meta property="og:title" content="背包问题">
<meta property="og:url" content="http://zjybjea.cn/2020/04/20/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="赵嘉熠的博客">
<meta property="og:description" content="背包问题给定一组物品，每种物品都有自己的重量和价值，现有一个背包，能承受的重量有限，在受限制的重量下，去取若干物品使总价值最大。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-20T12:45:50.000Z">
<meta property="article:modified_time" content="2020-10-17T05:29:59.488Z">
<meta property="article:author" content="Zhao Jiayi">
<meta property="article:tag" content="信息学">
<meta property="article:tag" content="算法">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://zjybjea.cn/2020/04/20/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>背包问题 | 赵嘉熠的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">赵嘉熠的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">ZJY'S BLOG</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://zjybjea.cn/2020/04/20/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/doggy.jpg">
      <meta itemprop="name" content="Zhao Jiayi">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵嘉熠的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          背包问题
        </h1>

        <div class="post-meta">
        	
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-20 20:45:50" itemprop="dateCreated datePublished" datetime="2020-04-20T20:45:50+08:00">2020-04-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E4%BF%A1%E6%81%AF%E5%AD%A6/" itemprop="url" rel="index"><span itemprop="name">信息学</span></a>
                </span>
            </span>

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2020/04/20/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/04/20/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="背包问题"><a href="#背包问题" class="headerlink" title="背包问题"></a>背包问题</h2><p><strong>给定一组物品，每种物品都有自己的重量和价值，现有一个背包，能承受的重量有限，在受限制的重量下，去取若干物品使总价值最大。</strong></p>
<a id="more"></a>
<h3 id="可拆分背包问题"><a href="#可拆分背包问题" class="headerlink" title="可拆分背包问题"></a>可拆分背包问题</h3><p>有$N$件物品和一个容积为$V$的背包。每件物品具有体积$c_i$和价值$w_i$。每件物品可以<strong>分割成任意大小</strong>后放入背包，且单位价值体积不变。该背包中最多可以放入的物品总价值为多少？</p>
<p>我们总是优先挑选<strong>单位体积内价值较高</strong>的物品放入背包内，所以对于每种物品，先计算其价值对体积的比值（性价比）$r_i=\frac{w_i}{c_i}$，之后对$r_i$进行排序后优先选择性价比较高的物品即可。</p>
<p>可拆分背包问题作为一种较为简单的背包，正是由于其可拆分的性质，所以能够使用贪心轻易地解决。</p>
<h3 id="01背包问题"><a href="#01背包问题" class="headerlink" title="01背包问题"></a>01背包问题</h3><p>​        <a target="_blank" rel="noopener" href="https://www.luogu.com.cn/problem/P1060">洛谷P1060 开心的金明</a></p>
<p>​        <a target="_blank" rel="noopener" href="https://www.luogu.com.cn/problem/P1048">洛谷P1048 采药</a></p>
<p>当前有$N$件物品和一个容积为$V$的背包。已知第i件物品的体积是$c_i$，价值是$w_i$。每种物品有且仅有一件，并且<strong>体积不可分割</strong>，只能选择<strong>放入或者不放入</strong>背包。现在需要选出若干件物品，在重量之和不超过V的条件下，使得总价值尽可能大。</p>
<p>算性价比?</p>
<p>反例：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>$c_i$</th>
<th>$w_i $</th>
<th>性价比</th>
</tr>
</thead>
<tbody>
<tr>
<td>4</td>
<td>8</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>5</td>
<td>$\frac{5}{3}$</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>$\frac{4}{3}$</td>
</tr>
</tbody>
</table>
</div>
<p>$V=6$</p>
<p>暴搜？</p>
<p>放或不放 $O(2^n)$</p>
<p><strong>动态规划：</strong></p>
<p>状态：前$i$个物品，总重量不超过$j$的前提下。所获得的最大价值为$dp[i][j]$。</p>
<p>转移方程：</p>
<script type="math/tex; mode=display">
j<c_i, dp[i][j]=dp[i-1][j]</script><script type="math/tex; mode=display">
c_i\leqslant j, dp[i][j]=max(dp[i-1][j],dp[i][j-c_i]+w_i)</script><p>核心代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= N; ++i) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;= V; ++j) &#123;</span><br><span class="line">        <span class="keyword">if</span>(j &gt;= c[i]) &#123;</span><br><span class="line">            dp[i][j] = max(dp[i - <span class="number">1</span>][j - c[i]] + w[i], dp[i - <span class="number">1</span>][j]);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            dp[i][j] = dp[i - <span class="number">1</span>][j];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>优化：转移时第一维只与<code>i-1</code>和<code>i</code>有关，因此我们可以将dp数组压缩</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> dp[<span class="number">2</span>][V];</span><br></pre></td></tr></table></figure>
<h3 id="多重背包问题"><a href="#多重背包问题" class="headerlink" title="多重背包问题"></a>多重背包问题</h3><p>​        <a target="_blank" rel="noopener" href="https://www.luogu.com.cn/problem/P1776">洛谷P1776 宝物筛选</a></p>
<p>有$N$种物品，第$i$种物品的体积是$c_i$，价值是$w_i$，每种物品的<strong>数量都是有限的</strong>，为$n_i$。现有容量为$V$的背包，请你放入若干物品，在总体积不超过$V$的条件下，使总价值尽可能大。</p>
<p>解法一：</p>
<p>将$N$种物品逐个拆分，得到$\sum{n_i}$个独立物品后用01背包解决。$O(V\sum{n_i})$</p>
<p>解法二：</p>
<p>在转移的过程中枚举第$i$个物品选取的数量$k$，和01背包的思想一样。</p>
<script type="math/tex; mode=display">
dp[i][j]=max(dp[i][j],dp[i-1][j-k*c_i]+k*w_i),0\leqslant k\leqslant n_i</script><p>复杂度$O(V\sum{n_i})$</p>
<p> 核心代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= N; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;= V; j++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> k = <span class="number">0</span>; k &lt;= n[i]; k++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (j &gt;= c[i] * k) &#123;</span><br><span class="line">                dp[i][j] = max(dp[i - <span class="number">1</span>][j - c[i] * k] + w[i] * k, dp[i][j]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这份代码和01背包相比不再有<code>else</code>部分了，因为<code>k=0</code>的时候<code>dp[i][j]=max(dp[i-1][j],dp[i][j])</code>，相当于01背包的<code>else</code>部分。</p>
<p>优化：</p>
<p>和01背包一样，由于转移方程只用到<code>i</code>和<code>i-1</code>，可以转成滚动数组，但由于<code>dp[i][j]</code>依赖初始值，所以在每次<code>j</code>循环开始之前一定要</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">memset</span>(dp[flag],<span class="number">0</span>,<span class="keyword">sizeof</span>(dp[flag]));</span><br></pre></td></tr></table></figure>
<h3 id="完全背包问题"><a href="#完全背包问题" class="headerlink" title="完全背包问题"></a>完全背包问题</h3><p><a target="_blank" rel="noopener" href="https://www.luogu.com.cn/problem/P1616">洛谷P1616 疯狂的采药</a></p>
<p>当前有$N$种物品，第$i$种物品的体积是$c_i$，价值是$w_i$。每种物品的<strong>数量是无限的</strong>，可以任意选择若干件。现有容量为$V$的背包，请你放入若干物品，使总体积不超过$V$，并且总价值尽可能大。</p>
<p>解法：虽然物品个数是无限的，但是实际上，由于背包容量有上限，每个物品最多选取的个数也是有限制的，这样可以转换成多重背包问题$n_i=\frac{V}{c_i}$，进而可以转换成01背包问题。</p>
<p>核心代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= N; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;= V; j++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> k = <span class="number">0</span>; k * c[i] &lt;= j; k++) &#123;</span><br><span class="line">            dp[i][j] = max(dp[i - <span class="number">1</span>][j - c[i] * k] + w[i] * k, dp[i][j]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>时间效率优化：</strong></p>
<p>我们可以注意到</p>
<script type="math/tex; mode=display">
dp[i][j]=max(dp[i-1][j],dp[i-1][j-c_i]+w_i,dp[i-1][j-c_i*2]+w_i*2...)</script><p>而</p>
<script type="math/tex; mode=display">
dp[i][j-c_i]=max(dp[i-1][j-c_i],dp[i-1][j-c_i*2]+w_i,dp[i-1][j-c_i*3]+w_i*2...)</script><p>也就是说，我们完全可以用<code>dp[i][j-c[i]]</code>的信息去更新<code>dp[i][j]</code>，而不用多此一举去枚举<code>k</code>了，转移可以直接变成如下</p>
<script type="math/tex; mode=display">
dp[i][j]=max(dp[i-1][j],dp[i][j-c_i]+w[i])</script><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;= v; j++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (j &gt;= c[i]) &#123;</span><br><span class="line">            dp[i][j] = max(dp[i][j - c[i]] + w[i], dp[i - <span class="number">1</span>][j]);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            dp[i][j] = dp[i - <span class="number">1</span>][j];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="背包问题的空间优化"><a href="#背包问题的空间优化" class="headerlink" title="背包问题的空间优化"></a>背包问题的空间优化</h3><p>二维转一维</p>
<p>以01背包为例：</p>
<p>原来的滚动数组代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> flag = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= N; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;= V; j++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (j &gt; c[i]) &#123;</span><br><span class="line">            dp[flag][j] = max(dp[<span class="number">1</span> - flag][j - c[i]] + w[i], dp[<span class="number">1</span> - flag][j]);    </span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            dp[flag][j] = dp[<span class="number">1</span> - flag][j];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    flag = <span class="number">1</span> - flag;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果我们把 <code>dp</code> 数组只开成一维表示体积，然后从大到小枚举体积，也就是从 $V$到$0$枚举，则当前引用的 <code>dp[j]</code>和<code>dp[j-c[i]]</code>仍然是计算第<code>i-1</code>件物品的结果，即二维状态下的<code>dp[1-flag][j]</code>, <code>dp[1-flag][j-c[i]]</code>,因为我们之前没有更新过<code>dp[1-flag][j]</code>,<code>dp[1-flag][j-c[i]]</code>的值。</p>
<p>故我们可以简化转移方程：</p>
<script type="math/tex; mode=display">
dp[j]=max(dp[j-c_i]+w_i,dp[j])</script><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; i++)&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = v; j &gt;= c[i]; j--) &#123;</span><br><span class="line">        dp[j] = max(dp[j - c[i]] + w[i], dp[j]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同理，多重背包：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= N; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = V; j &gt;= <span class="number">0</span>; j--) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> k = <span class="number">1</span>; k &lt;= n[i]; k++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (j &gt;= c[i] * k) &#123;</span><br><span class="line">                dp[j] = max(dp[j - c[i] * k] + w[i] * k, dp[j]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>完全背包：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = c[i]; j &lt;= v; j++) &#123;</span><br><span class="line">        dp[j] = max(dp[j - c[i]] + w[i], dp[j]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>节省了一半空间。</p>
<h3 id="扩展——分组背包问题"><a href="#扩展——分组背包问题" class="headerlink" title="扩展——分组背包问题"></a>扩展——分组背包问题</h3><p><a target="_blank" rel="noopener" href="https://www.luogu.com.cn/problem/P1757">洛谷P1757 通天之分组背包</a></p>
<p>当前有$N$种物品，第$i$种物品的体积是$c_i$，价值是$w_i$。每种物品有且仅有一件。<strong>这些东西被分为$K$组，同组的物品不能同时放入背包。</strong>现有容量为$V$的背包，请你放入若干物品，使总体积不超过$V$，并且总价值尽可能大。</p>
<p>解法：</p>
<p>在考虑最优解时，对于每一组内的物品有两种选择策略，要么选择组中的某一个物品放入背包，要么包内的任何一个物品都不选入背包。考虑到该策略与 01 背包的相似性，我们可以将<strong>一组物品</strong>抽象成单独的物品。首先使用朴素的 01 背包写法，用 <code>dp[i][j]</code> 表示枚举到第 $i$ 组物品时，背包体积不超过 $j$ 的最大价值和。</p>
<p>而与 01 背包不同的是，对于组内的每一个物品需要逐一枚举。</p>
<p>核心代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= K; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;= V; j++) &#123;</span><br><span class="line">        dp[i][j] = dp[i - <span class="number">1</span>][j];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> k = <span class="number">0</span>; k &lt; n[i]; k++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (j &gt;= c[i][k]) &#123;</span><br><span class="line">                dp[i][j] = max(dp[i][j], dp[i - <span class="number">1</span>][j - c[i][k]] + w[i][k]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><div class="table-container">
<table>
<thead>
<tr>
<th>背包类型</th>
<th>每种物品数量</th>
<th>基本解法</th>
</tr>
</thead>
<tbody>
<tr>
<td>01背包</td>
<td>1个</td>
<td>动规，双循环选最大值</td>
</tr>
<tr>
<td>多重背包</td>
<td>若干个</td>
<td>在01的基础上枚举选择的数量或将物品拆分成独立物品后按01来做</td>
</tr>
<tr>
<td>完全背包</td>
<td>无限</td>
<td>算出可放物品最大数量后按多重背包做</td>
</tr>
</tbody>
</table>
</div>
<p>作业：洛谷</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E4%BF%A1%E6%81%AF%E5%AD%A6/" rel="tag"># 信息学</a>
              <a href="/tags/%E7%AE%97%E6%B3%95/" rel="tag"># 算法</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/12/20/USACO-2019-December-Contest-Bronze/" rel="prev" title="USACO 2019 December Contest, Bronze">
      <i class="fa fa-chevron-left"></i> USACO 2019 December Contest, Bronze
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/07/13/%E7%96%AB%E6%83%85%E9%A1%B9%E7%9B%AE%E5%8C%96%E5%AD%A6%E4%B9%A0%E6%88%90%E6%9E%9C%E6%B1%87%E6%80%BB/" rel="next" title="疫情项目化学习成果汇总">
      疫情项目化学习成果汇总 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98"><span class="nav-text">背包问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E6%8B%86%E5%88%86%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98"><span class="nav-text">可拆分背包问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#01%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98"><span class="nav-text">01背包问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%9A%E9%87%8D%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98"><span class="nav-text">多重背包问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98"><span class="nav-text">完全背包问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98%E7%9A%84%E7%A9%BA%E9%97%B4%E4%BC%98%E5%8C%96"><span class="nav-text">背包问题的空间优化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%A9%E5%B1%95%E2%80%94%E2%80%94%E5%88%86%E7%BB%84%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98"><span class="nav-text">扩展——分组背包问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-text">总结</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Zhao Jiayi"
      src="/images/doggy.jpg">
  <p class="site-author-name" itemprop="name">Zhao Jiayi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">10</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:1423035286@qq.com" title="E-Mail → mailto:1423035286@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="/1423035286" title="QQ → 1423035286"><i class="fab fa-qq fa-fw"></i>QQ</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://140.143.166.224/" title="http:&#x2F;&#x2F;140.143.166.224&#x2F;" rel="noopener" target="_blank">BJEAOJ</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://124.205.120.153/" title="http:&#x2F;&#x2F;124.205.120.153&#x2F;" rel="noopener" target="_blank">BNDSOJ</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.luogu.com.cn/" title="https:&#x2F;&#x2F;www.luogu.com.cn&#x2F;" rel="noopener" target="_blank">洛谷</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://masonwang5914.github.io/" title="https:&#x2F;&#x2F;masonwang5914.github.io&#x2F;" rel="noopener" target="_blank">浩宇老师博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhao Jiayi</span>
</div>

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客
</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  
      

<script>
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      loader: {
          load: ['[tex]/mhchem'],
        source: {
          '[tex]/amsCd': '[tex]/amscd',
          '[tex]/AMScd': '[tex]/amscd'
        }
      },
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
          packages: {'[+]': ['mhchem']},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              let target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    (function () {
      var script = document.createElement('script');
      script.src = '//cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
      script.defer = true;
      document.head.appendChild(script);
    })();
  } else {
    MathJax.startup.document.state(0);
    MathJax.texReset();
    MathJax.typeset();
  }
</script>

    

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'egbHdezmbhNkGI8udEdOmtxs-gzGzoHsz',
      appKey     : 'ImiKQHShq5rs7Sy6krOc6mDo',
      placeholder: "快来评论吧~",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</body>
</html>
